﻿/*******************************************************************
 *     JameE
 *******************************************************************
  Copyright 2010 Clifford Champion and JameE contributors.
  
  This file is part of JameE.
  
  JameE is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  
  JameE is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with JameE.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************/
 
 
/// <reference path="~/Base/Classer.js" />
/// <reference path="~/Base/IncludeLoader.js" />

$include(
[

]);

$class(
"JameE.Engine.Image",
{
	/////////////////////
	// FIELDS
	/////////////
	_oImgNode: null,
	_oRect: null,
	_oDescriptionCached: null,
	_arr_fnOnLoaded: null,


	/////////////////////
	// CONSTRUCTOR
	/////////////
	_ctor: function (args) {
		var This = this;

		this._oRect = $argument("rectangle", "Math.Rectangle") || null;

		// load the image
		var strPath = $argument("path", "string") || null;
		$load(
			strPath, // path to image 
			function (oImgNode) { // callback when loaded
				
				// store node
				This._oImgNode = oImgNode;

				// store source dimensions?
				if (This._oRect == null) {
					This._oRect = new JameE.Math.Rectangle(
						{
							x: 0,
							y: 0,
							width: oImgNode.width,
							height: oImgNode.height
						}
					);
					This._oDescriptionCached = null;
				}

				// notify listeners
				if (This._arr_fnOnLoaded !== null) {
					var iNumListeners = This._arr_fnOnLoaded.length;
					for (var i = 0; i < iNumListeners; ++i) {
						This._arr_fnOnLoaded[i](This);
					}
					This._arr_fnOnLoaded = null;
				}
			}
		);
	},


	/////////////////////
	// METHODS
	/////////////
	getImageDescription: function () {
		if (this._oDescriptionCached === null) {
			var oDescription = {};
			oDescription.oImgNode = this._oImgNode;
			oDescription.oRect = this._oRect;
			this._oDescriptionCached = oDescription;
		}
		return this._oDescriptionCached;
	},

	isLoaded: function () {
		if (this._oImgNode === null) {
			return false;
		}
		else {
			return true;
		}
	},

	attachOnLoadedListener: function (fnListener) {
		/// <summary>Attachs a listener to be called when the image has loaded.</summary>
		$require_type(fnListener, "function");

		if (this.isLoaded()) {
			fnListener(this);
			return;
		}

		if (this._arr_fnOnLoaded === null) {
			this._arr_fnOnLoaded = [];
		}
		this._arr_fnOnLoaded.push(fnListener);
	}
});


$include_notify("Engine/Image.js");